package com.cnbot.camera.utils;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.SurfaceView;


/**
 * @author Wzz
 * 摄像头预览线程
 */
public class VideoCanvasCameraThread extends Thread {
    public SurfaceView mSurfaceView;
    public boolean canvasCameraUpThreadRunFlag = false;
    /**
     * 预览画笔
     */
    private Paint mPaint = new Paint();
    /**
     * 预览数据宽度
     */
    private int previewWidth;
    /**
     * 预览数据高度
     */
    private int previewHeight;
    /**
     * 数据长度
     */
    private int frameSize;
    private int[] mRGBData;

    public VideoCanvasCameraThread(SurfaceView surfaceView, int width, int height) {
        mSurfaceView = surfaceView;
        previewWidth = width;
        previewHeight = height;
        frameSize = width * height;
        mRGBData = new int[frameSize];
    }

    @Override
    public void run() {
        super.run();
        Canvas canvas;
        Bitmap bitmap;
        while (true) {
            if (canvasCameraUpThreadRunFlag) {
                canvas = mSurfaceView.getHolder().lockCanvas();
                if (canvas != null) {
                    Rect sRect = new Rect(0, 0, previewWidth, previewHeight);
                    Rect dRect = new Rect(0, 0, canvas.getWidth(), canvas.getHeight());
                    bitmap = Bitmap.createBitmap(mRGBData, previewWidth, previewHeight, Bitmap.Config.ARGB_8888);
                    canvas.drawBitmap(bitmap, sRect, dRect, mPaint);
                    BitmapUtils.recycleBitmap(bitmap);
                    mSurfaceView.getHolder().unlockCanvasAndPost(canvas);
                }
                canvasCameraUpThreadRunFlag = false;
            } else {
                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }
    }

    /**
     * 设置画布参数
     *
     * @param width
     * @param height
     */
    public void setDataParameter(int width, int height) {
        previewWidth = width;
        previewHeight = height;
        frameSize = width * height;
        mRGBData = new int[frameSize];
    }

    /**
     * 写入预览数据
     */
    public void setCanvasNv21UpData(int[] mRGBData) {
        this.mRGBData = mRGBData;
    }

    /**
     * 获取图片
     *
     * @return
     */
    public int[] getRGBData() {
        return mRGBData;
    }

    public boolean isCanvasCameraUpThreadRunFlag() {
        return canvasCameraUpThreadRunFlag;
    }

    public void setCanvasCameraUpThreadRunFlag(boolean canvasCameraUpThreadRunFlag) {
        this.canvasCameraUpThreadRunFlag = canvasCameraUpThreadRunFlag;
    }

}
